package cn.zj.note.view.event;

import cn.zj.note.MainApp;
import cn.zj.note.todo.Todo;
import cn.zj.note.todo.TodoManager;
import cn.zj.note.util.StrFmtUtil;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.ListView;
import javafx.scene.control.TextInputDialog;
import javafx.util.Pair;

import java.util.Optional;

public class AddTodoEventHandler implements EventHandler<ActionEvent> {
    private ListView<Todo> listView;

    public AddTodoEventHandler(ListView<Todo> listView) {
        this.listView = listView;
    }

    @Override
    public void handle(ActionEvent actionEvent) {
        TextInputDialog dialog = new TextInputDialog();
        dialog.setTitle("添加任务");
        dialog.setHeaderText("");
        dialog.setContentText("任务内容：");

        Optional<String> result = dialog.showAndWait();
        result.ifPresent(taskContent -> {
            // 在这里添加任务的逻辑
            Pair<String, String> pair = StrFmtUtil.splitUrlFromContent(taskContent);
            Todo newTodo = new Todo(pair.getKey());
            newTodo.setUrl(pair.getValue());
            TodoManager.getInstance().addTodo(newTodo);
            System.out.println("=======add==="+newTodo);
            ObservableList<Todo> items = FXCollections.observableArrayList(TodoManager.getInstance().getTodos());
            this.listView.setItems(items);
            MainApp.refreshListView();
        });
    }
}
